<?php
/**
 * Created by PhpStorm.
 * User: djh
 * Date: 2016/11/1
 * Time: 11:25
 */

namespace member\action;
use common\action\CommonAction as BaseAction;
use herosphp\bean\Beans;
use herosphp\utils\AjaxResult;
use member\service\LoginService;
use herosphp\core\WebApplication;
use herosphp\core\Loader;

Loader::import('member.service.LoginService');

class CommonAction extends BaseAction
{

	/*
	* Login 控制器 
	* 使用：所有继承自Member\CommonAction 控制器
	* 判断是否登录 $this->_user->hasLogin()
	* 拿属性 $this->_user->id , $this->_user->group_id, $this->_user->username ... 
	* 拿当前登录用户的信息  $this->_user->getMyInfo() 
	* 登录与退出  $this->_user->login($username,$password) , $this->_user->logout() 
	 */
	protected $_user;
	public function __construct()
	{
		$this->_user = new LoginService();
		parent::__construct();
	}
	public function C_start()
	{
		parent::C_start();
		$this->assign('keyword',C('keyword'));
		$this->assign('title',C('title'));
		$this->assign('moduletitle',C('title'));
		$this->assign('description',C('description'));
		$settingService = Beans::get('admin.adminSetting.service');
		$worktimestr = $settingService->getWorktimeStr();

		$qqArr = $settingService->getQa(5);
		$this->assign('qqArr',$qqArr);
		$this->assign('cs_phone',C('cs_phone'));
		$this->assign('pro_unit',C('pro_unit'));
		$this->assign('pro_std',C('pro_std'));
		$this->assign('wx_qr',C('wx_qr'));
		$this->assign('worktimestr',$worktimestr);


		$app  = WebApplication::getInstance();
		$request = $app->getHttpRequest();
		$module = $request->getModule();
		$action = $request->getAction();
		$method = $request->getMethod();
		$navs = Beans::get('admin.adminNav.service')->getAvailNavCached();
        //左侧导航栏 签约信息
        $authStatus = $this->_user->getSignInfo('ischecked');//实名认证状态 1:审核中 2：已通过 3： 未通过
        $bankStatus = $this->_user->getSignInfo('sign_status');//银行签约 0:未签约 1：已签约 2： 已解决

        $this->assign('authStatus',$authStatus);
        $this->assign('bankStatus',$bankStatus);
		//获取页脚位置的单页信息
		$this->assign("singles",$this->getSinglepage());
		$this->assign("adBotton",$this->getAd());
		$this->assign("cartCount",$this->getCartCount());
		$this->assign('remindCount',$this->getRemindCount());

		$this->assign('navs',$navs);

		//站点关闭，跳转页面
		if(C('site_enabled')=='off'){

			$url = C('site_down_page');

			$url = (strpos($url,'http')===0)?$url:"/{$url}";

			echo "<meta http-equiv='refresh' content='5;URL={$url}'>站点已关闭,5秒后跳转到指定页面！";
			die;
		}

		//登录、注册页放行、购物车也放行（游客可以添加购物车）
		if($action == 'login' || $action == 'reg' || ($action == 'order' && ($method == 'cart' || $method == 'getCart' || $method == 'delCartProduct')))
		{
			return ;
		}




		if(!$this->_user->hasLogin())
		{
			header('location:'.url('/member/login/index?dir='.urlencode($_SERVER['REQUEST_URI'])));
			exit(0);
		}
		$this->assign('userphoto',$this->_user->__get('photo'));
		$this->assign('username' , $this->_user->username);

	}

    /**
     * 更新数据
     * @author Liuyi
     * @Create 2016-11-1 11:13:50
     * @param array $data
     * @param $id
     * @param $callback 回调函数
     */
    public function __update(array $data, $id, $callback=null) {

        if ( empty($data) || empty($id) ) AjaxResult::ajaxFailtureResult();

        $data['updatetime'] = date('Y-m-d H:i:s');

        $service = Beans::get($this->getServiceBean());
        if ( $service->update($data, $id) ) {
            if ( !is_null($callback) ) {
                call_user_func($callback, $service);
            }
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }

    }

	/**
	 * 获取用户页尾的单页数据
	 * @Author horse
	 * @Create 2016-11-17
	 * @return singles array 返回多维数组
	 */
	public function getSinglepage()
	{
		//获取单页类型
		$singlePageCate = Beans::get('information.informationSinglepageCate.service')->getItems(array(),array(),array("sort_index"=>1),3);
		foreach($singlePageCate as $cate)
		{
			$child = null;
			$singlePage = Beans::get("information.informationSinglepage.service")
					->getItems(array("cate_id"=>array('$in'=>$cate['id'])),array(),array("sort_index"=>1),7);
			if($singlePage)
			{
				$child = $singlePage;
			}
			$singles[] = array("id"=>$cate['id'],"name"=>$cate['name'],"child"=>$child);
		}
		return $singles;
	}

	/**
	 * 获取中心页尾的广告
	 * @Author horse
	 * @Create 2016-11-17
	 * @return ads array 返回多维数组
	 */
	public function getAd()
	{
		//array('ad_place_id'=>2) 暂时写死广告位置的id
		$Ad = Beans::get("information.informationAd.service")->getItem(array('ad_place_key'=>"12c65c3744eca390077f0010f27734f7"));
		if($Ad["target"]==0){
			$Ad['target']="_self";
		}else{
			$Ad["target"] ="_blank";
		}
		return $Ad;
	}
	/**
	 * 获取购物车商品数量
	 * @Author horse
	 * @Create 2016-11-18
	 * @return $count int
	 */
	public function getCartCount()
	{
        $cartService = Beans::get('trading.tradingCart.service');
        $count = 0;
        if($this->_user->hasLogin()){
            $member_id = $this->_user->__get('id');
            $item = $cartService->getCarts($member_id);
            $productIdArr = $item['productIdArr']?$item['productIdArr']:array();
            $productIdArr_c = json_decode($_COOKIE['cartInfo']);
            $need_arr = array_diff($productIdArr_c,$productIdArr);
            foreach($need_arr as $v){
                $cartService->addCartProduct($member_id, $v);
            }
            $item = $cartService->getCarts($member_id);
            $productIdArr = $item['productIdArr']?$item['productIdArr']:array();
            setCookie('cartInfo',json_encode($productIdArr),time()+3600*24*365,'/');
            $count = $cartService->CartProductTotal($member_id);
        }else{
            $count = count(json_decode($_COOKIE['cartInfo']));
        }
		return $count;
	}
	/**
	 * 获取用未读消息都是条数
	 * @param $memberId
	 */
	public function getRemindCount()
	{
		$member_id = $this->_user->id;
		$remindService = Beans::get('message.messageRemind.service');
		$count = $remindService->getRemindTotal($member_id);
		return $count;
	}
    /**
     * @override
     * @param $message
     * @param $url
     */
    public function message( $message, $url ) {

        $this->assign('message', $message);
        $this->assign('url', $url);
        $this->setView('unsign_tip');

    }

    /**
     * 短信超时方法，统一为5分钟
     */
    public function timeOut(){
        if(time() - $_SESSION['mpe_member']['time'] > 300){
            unset($_SESSION['mpe_member']['vcode']);
            unset($_SESSION['mpe_member']['time']);
        }

    }
}
